<template>
  <div>
    <!-- <div class="n-layout-page-header">
      <n-card :bordered="false" title="角色权限管理">
        页面数据为 Mock 示例数据，非真实数据。
      </n-card>
    </div> -->
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :dataSource="roleDataSource" :row-key="(row) => row.roleId" ref="actionRef"
                  :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :pagination="false">
        <template #tableTitle>
          <n-button type="primary" @click="handlerAddRole">
            <template #icon>
              <n-icon>
                <PlusOutlined/>
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>
        <template #action>
          <TableAction/>
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
            block-line
            cascade
            checkable
            :virtual-scroll="true"
            :data="treeDataSource"
            :expandedKeys="expandedKeys"
            :checked-keys="checkedKeys"
            style="max-height: 950px; overflow: hidden"
            @update:checked-keys="checkedTree"
            @update:expanded-keys="onExpandedKeys"/>
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>

    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
      <template #default>
        <BasicForm @register="register" class="basicForm">
        </BasicForm>
      </template>
    </basicModal>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, unref, h, onMounted, compile, computed} from 'vue';
import {c, useMessage} from 'naive-ui';
import {BasicTable, TableAction} from '@/components/Table';
import {getRoleList, updateRoleAuth, UpdateRoleAuth} from '@/api/system/role';
import {getBasicList, getMenuList} from '@/api/system/menu';
import {columns, editCloumns} from './columns';
import {PlusOutlined} from '@vicons/antd';
import {getTreeAll} from '@/utils';
import {useRouter} from 'vue-router';
import {basicModal, useModal} from '@/components/Modal/index';
import {BasicForm, useForm} from '@/components/Form/index';
import {DeleteOutlined, EditOutlined} from '@vicons/antd';

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const actionRef = ref();

const showModal = ref(false);
const showEdit = ref(false);
const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref('');
const treeDataSource = ref([]);
const expandedKeys = ref([]);
const checkedKeys = ref([]);
const roleDataSource = ref([]);
const updateRole = ref({});


const actionColumn = reactive({
  width: 280,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record: any) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '菜单权限',
          type: 'warning',
          onClick: handleMenuAuth.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
        {
          label: '编辑',
          type: 'info',
          icon: EditOutlined,
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          // auth: ['basic_list'],
        },
        {
          label: '删除',
          type: 'error',
          icon: DeleteOutlined,
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          // auth: ['basic_list'],
        },
      ],
    });
  },
});

const [modalRegister, {openModal, closeModal, setSubLoading, setProps}] = useModal({
  title: '编辑',
});
const [register, {submit, setFieldsValue, getFieldsValue}] = useForm({
  gridProps: {cols: 1},
  collapsedRows: 3,
  labelWidth: 120,
  layout: 'horizontal',
  submitButtonText: '提交保存',
  showActionButtonGroup: false,
  schemas: editCloumns
});

async function okModal() {
  try {
    const formRes = await submit();
    let params = Object.assign(unref(updateRole), formRes)
    console.log(params);
    closeModal();
    reloadTable()
    message.success('提交成功');
  } catch (e) {
    message.error('验证失败，请填写完整信息');
    setSubLoading(false);
  }
}

const loadDataTable = async (res: any) => {
  // let _params = {
  //   ...unref(params),
  //   ...res,
  // };
  return await getRoleList();
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  loadDataSource()
  actionRef.value.reload();
}

function handlerAddRole() {
  setProps({
    title: '添加',
  });
  openModal()
}

async function confirmForm(e: any) {
  e.preventDefault();
  try {
    formBtnLoading.value = true;
    const {roleName, roleid, desc,} = unref(updateRole)
    let params = {
      roleName,
      roleId: roleid,
      roleDesc: desc,
      authLists: checkedKeys.value.toString()
    }
    const tparams = params as UpdateRoleAuth
    await updateRoleAuth(tparams)
    message.success('修改成功,下次登录生效');
    setTimeout(() => {
      showModal.value = false;
      reloadTable();
    });
  } finally {
    formBtnLoading.value = false;
  }
}

async function handleEdit(record: any) {
  updateRole.value = unref(record)
  setProps({
    title: '编辑'
  });
  await openModal();
  setFieldsValue(record)
  // router.push({ name: 'basic-info', params: { id: record.id } });
}

function handleDelete(record: Recordable) {
  console.log('点击了删除', record);
  message.info('点击了删除');
}

function handleMenuAuth(record: any) {
  editRoleTitle.value = `分配 ${record.desc} 的菜单权限`;
  checkedKeys.value = record.authArrs.map(re => re.ps_id);
  console.log(checkedKeys);
  updateRole.value = record
  showModal.value = true;
}

function checkedTree(keys) {
  checkedKeys.value = [...keys];
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = treeDataSource.value.map((item: any) => item.key) as [];
  }
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = getTreeAll(treeDataSource.value);
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

onMounted(async () => {
  loadDataSource()
});

async function loadDataSource() {
  const treeMenuList = await getBasicList();
  const roleList = await getRoleList();
  let menuList = handlerMenuList(treeMenuList);
  console.log(menuList);
  expandedKeys.value = menuList.map((item) => item.key);
  treeDataSource.value = menuList;
  roleDataSource.value = roleList
}


function handlerMenuList(treeMenuList: any): any[] {
  return treeMenuList.map((item: any) => {
    const {psId, psName, psUrl} = item;
    return {
      label: psName,
      key: psId,
      path: psUrl,
      children: []
    }
  })
}
</script>

<style lang="less" scoped>
</style>
